<template>
  <div class="lov-demo-page">
    <div class="page-header">
      <h2>LOV 使用演示</h2>
      <p>演示如何使用LOV选择器组件</p>
    </div>

    <a-card class="demo-card">
      <template #title>
        <span>学生信息查询示例</span>
      </template>

      <a-form :model="form" :label-col="{ style: { width: '120px' } }">
        <a-form-item label="选择学生">
          <lov-select
            v-model="form.studentId"
            code="LOV_STUDENT_DYNAMIC"
            placeholder="请选择学生"
            @change="handleStudentChange"
            style="width: 300px"
          />
        </a-form-item>

        <a-form-item label="学号">
          <a-input v-model:value="form.studentId" readonly style="width: 300px" />
        </a-form-item>

        <a-form-item label="姓名">
          <a-input v-model:value="form.studentName" readonly style="width: 300px" />
        </a-form-item>

        <a-form-item label="年龄">
          <a-input v-model:value="form.studentAge" readonly style="width: 300px" />
        </a-form-item>
      </a-form>

      <a-divider />

      <div class="info-section">
        <h3>选中的数据：</h3>
        <pre>{{ selectedData || '暂无选择' }}</pre>
      </div>
    </a-card>

    <a-card class="demo-card">
      <template #title>
        <span>使用说明</span>
      </template>

      <div class="instructions">
        <h3>功能特性：</h3>
        <ul>
          <li>✅ 支持自定义SQL配置数据源</li>
          <li>✅ 支持多条件动态查询</li>
          <li>✅ 支持分页展示</li>
          <li>✅ 支持自定义列配置（显示列、查询字段）</li>
          <li>✅ 支持双击选择或单击选择</li>
          <li>✅ 支持回显（根据值自动显示文本）</li>
          <li>✅ 支持清空选择</li>
        </ul>

        <h3>使用方法：</h3>
        <div class="code-block">
          <pre><code>&lt;lov-select
  v-model="studentId"
  code="LOV_STUDENT_DYNAMIC"
  placeholder="请选择学生"
  @change="handleChange"
/&gt;</code></pre>
        </div>

        <h3>配置步骤：</h3>
        <ol>
          <li>在"LOV配置管理"页面新建LOV配置</li>
          <li>填写基本信息：代码、名称、SQL语句、值字段、显示字段等</li>
          <li>配置显示列：设置列名称、字段名、列宽、是否可查询等</li>
          <li>保存配置</li>
          <li>在页面中使用 <code>&lt;lov-select&gt;</code> 组件，指定配置代码即可</li>
        </ol>
      </div>
    </a-card>

    <a-card class="demo-card">
      <template #title>
        <span>自定义Query查询示例（支持MyBatis动态SQL）</span>
      </template>

      <a-form :model="customQueryForm" :label-col="{ style: { width: '120px' } }">
        <a-form-item label="学生选择">
          <lov-select
            ref="customLovRef"
            v-model="customQueryForm.studentId"
            code="LOV_STUDENT_DYNAMIC"
            placeholder="点击使用自定义查询"
            @change="handleCustomQueryChange"
            style="width: 300px"
          />
        </a-form-item>

        <a-form-item label="年龄范围">
          <a-input-number
            v-model:value="customQueryForm.minAge"
            :min="0"
            :max="100"
            placeholder="最小年龄"
            style="width: 140px"
          />
          <span style="margin: 0 10px">-</span>
          <a-input-number
            v-model:value="customQueryForm.maxAge"
            :min="0"
            :max="100"
            placeholder="最大年龄"
            style="width: 140px"
          />
        </a-form-item>

        <a-form-item label="姓名关键词">
          <a-input
            v-model:value="customQueryForm.nameKeyword"
            placeholder="输入姓名关键词"
            style="width: 300px"
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="handleCustomQuery">
            <template #icon><SearchOutlined /></template>
            使用自定义参数查询
          </a-button>
          <a-button style="margin-left: 8px" @click="handleResetCustomQuery">重置查询</a-button>
        </a-form-item>
      </a-form>

      <div class="info-section">
        <h3>说明：</h3>
        <p>此示例展示如何使用 <code>query()</code> 方法进行自定义参数查询：</p>
        <ul>
          <li>支持传入自定义参数对象</li>
          <li>后端支持MyBatis动态SQL（<code>&lt;if&gt;</code>、<code>&lt;where&gt;</code>等标签）</li>
          <li>支持 <code>#{xxx}</code> 参数占位符，自动防SQL注入</li>
          <li>⭐ 配置SQL时<strong>无需手动添加</strong> <code>&lt;script&gt;</code> 标签，后端自动处理</li>
          <li>类似KendoUI的query功能，更加灵活</li>
        </ul>

        <div class="code-block">
          <pre><code>// SQL配置（直接写SQL，无需&lt;script&gt;标签）
SELECT stu_id, stu_name, stu_age
FROM student
&lt;where&gt;
  &lt;if test="minAge != null"&gt;
    AND stu_age &gt;= #{minAge}
  &lt;/if&gt;
  &lt;if test="maxAge != null"&gt;
    AND stu_age &lt;= #{maxAge}
  &lt;/if&gt;
&lt;/where&gt;

// 前端调用
lovRef.value.query({
  minAge: 18,
  maxAge: 25,
  nameKeyword: '张'
})</code></pre>
        </div>
      </div>

      <div class="info-section" v-if="customQueryResult">
        <h3>选中的数据：</h3>
        <pre>{{ customQueryResult }}</pre>
      </div>
    </a-card>

    <a-card class="demo-card">
      <template #title>
        <span>动态SQL测试 - 搜索类型切换（<code>&lt;choose&gt;</code>标签）</span>
      </template>

      <a-form :model="dynamicSearchForm" :label-col="{ style: { width: '120px' } }">
        <a-form-item label="学生选择">
          <lov-select
            ref="dynamicSearchRef"
            v-model="dynamicSearchForm.studentId"
            code="LOV_STUDENT_SEARCH"
            placeholder="点击进行动态搜索"
            @change="handleDynamicSearchChange"
            style="width: 300px"
          />
        </a-form-item>

        <a-form-item label="搜索类型">
          <a-radio-group v-model:value="dynamicSearchForm.searchType">
            <a-radio value="id">按学号</a-radio>
            <a-radio value="name">按姓名</a-radio>
            <a-radio value="age">按年龄</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="搜索值">
          <a-input
            v-model:value="dynamicSearchForm.searchValue"
            :placeholder="getSearchPlaceholder()"
            style="width: 300px"
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="handleDynamicSearch">
            <template #icon><SearchOutlined /></template>
            动态搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="handleResetDynamicSearch">重置</a-button>
        </a-form-item>
      </a-form>

      <div class="info-section">
        <h3>说明：</h3>
        <p>此示例展示 MyBatis <code>&lt;choose&gt;</code> 标签的使用：</p>
        <ul>
          <li>根据搜索类型动态切换SQL条件</li>
          <li>支持按学号精确匹配、按姓名模糊查询、按年龄查询</li>
          <li>后端使用 <code>&lt;when&gt;</code> 和 <code>&lt;otherwise&gt;</code> 标签</li>
          <li>⭐ 直接写SQL即可，无需 <code>&lt;script&gt;</code> 标签</li>
        </ul>
      </div>

      <div class="info-section" v-if="dynamicSearchResult">
        <h3>选中的数据：</h3>
        <pre>{{ dynamicSearchResult }}</pre>
      </div>
    </a-card>

    <a-card class="demo-card">
      <template #title>
        <span>动态SQL测试 - 批量条件（<code>&lt;foreach&gt;</code>标签）</span>
      </template>

      <a-form :model="batchQueryForm" :label-col="{ style: { width: '120px' } }">
        <a-form-item label="学生选择">
          <lov-select
            ref="batchQueryRef"
            v-model="batchQueryForm.studentId"
            code="LOV_STUDENT_BATCH"
            placeholder="点击进行批量查询"
            @change="handleBatchQueryChange"
            style="width: 300px"
          />
        </a-form-item>

        <a-form-item label="学号列表">
          <a-input
            v-model:value="batchQueryForm.idListStr"
            placeholder="输入多个学号，用逗号分隔，例如：001,002,003"
            style="width: 400px"
          />
        </a-form-item>

        <a-form-item label="年龄列表">
          <a-input
            v-model:value="batchQueryForm.ageListStr"
            placeholder="输入多个年龄，用逗号分隔，例如：18,19,20"
            style="width: 400px"
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="handleBatchQuery">
            <template #icon><SearchOutlined /></template>
            批量查询
          </a-button>
          <a-button style="margin-left: 8px" @click="handleResetBatchQuery">重置</a-button>
        </a-form-item>
      </a-form>

      <div class="info-section">
        <h3>说明：</h3>
        <p>此示例展示 MyBatis <code>&lt;foreach&gt;</code> 标签的使用：</p>
        <ul>
          <li>支持传入数组进行IN查询</li>
          <li>可以同时使用多个foreach条件</li>
          <li>自动处理集合参数</li>
          <li>⭐ 配置SQL时直接写即可，后端自动添加 <code>&lt;script&gt;</code> 标签</li>
        </ul>
      </div>

      <div class="info-section" v-if="batchQueryResult">
        <h3>选中的数据：</h3>
        <pre>{{ batchQueryResult }}</pre>
      </div>
    </a-card>

    <a-card class="demo-card">
      <template #title>
        <span>表单提交示例</span>
      </template>

      <a-form :model="submitForm" :label-col="{ style: { width: '120px' } }">
        <a-form-item label="学生">
          <lov-select
            v-model="submitForm.studentId"
            code="LOV_STUDENT_DYNAMIC"
            placeholder="请选择学生"
            style="width: 300px"
          />
        </a-form-item>

        <a-form-item label="备注">
          <a-textarea
            v-model:value="submitForm.remark"
            :rows="3"
            placeholder="请输入备注"
            style="width: 300px"
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="handleSubmit">提交</a-button>
          <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>

      <div class="info-section" v-if="submitResult">
        <h3>提交的数据：</h3>
        <pre>{{ submitResult }}</pre>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { SearchOutlined } from '@ant-design/icons-vue'
import LovSelect from '@/components/lov/LovSelect.vue'

const form = reactive({
  studentId: '',
  studentName: '',
  studentAge: ''
})

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const selectedData = ref<any>(null)

// 自定义Query查询表单
const customQueryForm = reactive({
  studentId: '',
  minAge: null as number | null,
  maxAge: null as number | null,
  nameKeyword: ''
})

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const customQueryResult = ref<any>(null)
const customLovRef = ref()

// 动态搜索表单（<choose>标签测试）
const dynamicSearchForm = reactive({
  studentId: '',
  searchType: 'id' as 'id' | 'name' | 'age',
  searchValue: ''
})

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const dynamicSearchResult = ref<any>(null)
const dynamicSearchRef = ref()

// 批量查询表单（<foreach>标签测试）
const batchQueryForm = reactive({
  studentId: '',
  idListStr: '',
  ageListStr: ''
})

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const batchQueryResult = ref<any>(null)
const batchQueryRef = ref()

const submitForm = reactive({
  studentId: '',
  remark: ''
})

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const submitResult = ref<any>(null)

// 学生选择变化
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function handleStudentChange(row: any) {
  console.log('选中的学生：', row)
  selectedData.value = row

  if (row) {
    form.studentName = row.stu_name || ''
    form.studentAge = row.stu_age || ''
  } else {
    form.studentName = ''
    form.studentAge = ''
  }
}

// 自定义Query查询
async function handleCustomQuery() {
  if (!customLovRef.value) {
    message.error('组件引用未初始化')
    return
  }

  try {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const params: Record<string, any> = {}

    if (customQueryForm.minAge !== null) {
      params.minAge = customQueryForm.minAge
    }
    if (customQueryForm.maxAge !== null) {
      params.maxAge = customQueryForm.maxAge
    }
    if (customQueryForm.nameKeyword) {
      params.nameKeyword = customQueryForm.nameKeyword
    }

    console.log('自定义查询参数：', params)
    await customLovRef.value.openDialogWithCustomQuery(params)
    message.success('查询成功')
  } catch (error) {
    console.error('自定义查询失败：', error)
  }
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function handleCustomQueryChange(row: any) {
  console.log('自定义查询选中：', row)
  customQueryResult.value = row
}

function handleResetCustomQuery() {
  customQueryForm.minAge = null
  customQueryForm.maxAge = null
  customQueryForm.nameKeyword = ''
  customQueryForm.studentId = ''
  customQueryResult.value = null
}

// 动态搜索
async function handleDynamicSearch() {
  if (!dynamicSearchRef.value) {
    message.error('组件引用未初始化')
    return
  }

  if (!dynamicSearchForm.searchValue) {
    message.warning('请输入搜索值')
    return
  }

  try {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const params: Record<string, any> = {
      searchType: dynamicSearchForm.searchType,
      searchValue: dynamicSearchForm.searchValue
    }

    await dynamicSearchRef.value.openDialogWithCustomQuery(params)
    message.success('搜索成功')
  } catch (error) {
    console.error('动态搜索失败：', error)
  }
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function handleDynamicSearchChange(row: any) {
  dynamicSearchResult.value = row
}

function handleResetDynamicSearch() {
  dynamicSearchForm.searchType = 'id'
  dynamicSearchForm.searchValue = ''
  dynamicSearchForm.studentId = ''
  dynamicSearchResult.value = null
}

function getSearchPlaceholder() {
  switch (dynamicSearchForm.searchType) {
    case 'id':
      return '输入学号，例如：001'
    case 'name':
      return '输入姓名，例如：张三'
    case 'age':
      return '输入年龄，例如：20'
    default:
      return '请输入搜索值'
  }
}

// 批量查询
async function handleBatchQuery() {
  if (!batchQueryRef.value) {
    message.error('组件引用未初始化')
    return
  }

  if (!batchQueryForm.idListStr && !batchQueryForm.ageListStr) {
    message.warning('请至少输入一个查询条件')
    return
  }

  try {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const params: Record<string, any> = {}

    if (batchQueryForm.idListStr) {
      params.idList = batchQueryForm.idListStr
        .split(',')
        .map(id => id.trim())
        .filter(id => id)
    }

    if (batchQueryForm.ageListStr) {
      params.ageList = batchQueryForm.ageListStr
        .split(',')
        .map(age => parseInt(age.trim()))
        .filter(age => !isNaN(age))
    }

    await batchQueryRef.value.openDialogWithCustomQuery(params)
    message.success('查询成功')
  } catch (error) {
    console.error('批量查询失败：', error)
  }
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function handleBatchQueryChange(row: any) {
  batchQueryResult.value = row
}

function handleResetBatchQuery() {
  batchQueryForm.idListStr = ''
  batchQueryForm.ageListStr = ''
  batchQueryForm.studentId = ''
  batchQueryResult.value = null
}

// 提交表单
function handleSubmit() {
  if (!submitForm.studentId) {
    message.warning('请选择学生')
    return
  }

  submitResult.value = {
    studentId: submitForm.studentId,
    remark: submitForm.remark,
    submitTime: new Date().toLocaleString()
  }

  message.success('提交成功')
}

function handleReset() {
  submitForm.studentId = ''
  submitForm.remark = ''
  submitResult.value = null
}
</script>

<style scoped>
.lov-demo-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
}

.page-header p {
  margin: 0;
  color: #666;
}

.demo-card {
  margin-bottom: 20px;
}

.info-section {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.info-section h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.info-section pre {
  margin: 0;
  background: #fff;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
}

.instructions h3 {
  margin-top: 20px;
  margin-bottom: 10px;
  color: #1890ff;
}

.instructions ul {
  margin: 10px 0;
  padding-left: 20px;
}

.instructions ul li {
  margin: 8px 0;
  line-height: 1.6;
}

.instructions ol {
  margin: 10px 0;
  padding-left: 20px;
}

.instructions ol li {
  margin: 8px 0;
  line-height: 1.6;
}

.code-block {
  background: #2c3e50;
  color: #fff;
  padding: 15px;
  border-radius: 4px;
  margin: 10px 0;
}

.code-block pre {
  margin: 0;
}

.code-block code {
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
}

code {
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', Courier, monospace;
  color: #e74c3c;
}
</style>

